<template>
  <div v-loading="!uploadFinsh">
    <el-button
      class="table-btn"
      size="small"
      type="primary"
      :icon="icon"
      @click="() => $refs['file-input'].click()"
    >{{ uploadText }}</el-button>
    <input ref="file-input" :multiple="false" type="file" style="display: none;" @change="handleUploadImg">
  </div>
</template>

<script>
import { post } from '@/utils/request'
export default {
  name: 'WxUploadButton',
  props: {
    uploadText: {
      type: String,
      default: '点击上传'
    },
    icon: {
      type: String,
      default: 'el-icon-upload2'
    },
    api: {
      type: String,
      default: '/api/adminPortal/uploadFile'
    }
  },
  data() {
    return {
      percent: 0,
      uploadFinsh: true
    }
  },
  methods: {
    handleUploadImg(e) {
      const myFile = e.target.files[0]

      if (!myFile) {
        return
      }
      this.uploadFinsh = false
      const formData = new FormData()
      formData.append('file', myFile)
      post(this.api, formData, {
        onUploadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            var complete =
                  (((progressEvent.loaded / progressEvent.total) * 100) | 0)
            this.percent = complete
          }
        }
      }).then((res) => {
        if (res.code === 200) {
          e.target.value = ''
          this.$emit('upload-succ', { response: res, name: myFile.name })
        }
      })
    }
  }
}
</script>
